package com.lovo.bbs.servlet.admin;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lovo.bbs.bo.BoardBo;
import com.lovo.bbs.bo.ForumBo;
import com.lovo.bbs.bo.ForumStatBo;
import com.lovo.bbs.vo.BoardVo;
import com.lovo.bbs.vo.ForumStatVo;
import com.lovo.bbs.vo.ForumVo;

/**
 * 管理板块
 * @author tiancen2001
 *
 */
public class BoardUpdateServlet extends HttpServlet {

	private static final long serialVersionUID = 9108739492239778462L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 板块ID
		int boradID = 0;
		String asBoardid = req.getParameter("boardid");
		if ("".equals(asBoardid) || asBoardid == null) {
			boradID = 0;
		} else {
			boradID = Integer.parseInt(asBoardid);
		}
		// 板块名
		String boardName = req.getParameter("boardname");
		if (boardName == null) {
			boardName = "";
		} else {
			boardName = new String(boardName.getBytes("ISO-8859-1"), "utf-8");
		}
		// 操作类型
		int opType = Integer.parseInt(req.getParameter("opType"));
		// 原页码,返回原页面时使用
		int queryPage = Integer.parseInt(req.getParameter("queryPage"));
		if (queryPage == 0) {
			queryPage = 1;
		}

		BoardVo vo = new BoardVo();
		vo.setBoardID(boradID);
		vo.setBoardName(boardName);
		int dataChanged = 0;

		ServletContext context = req.getSession().getServletContext();

		BoardBo boardBo = new BoardBo();
		ForumStatBo forumStatBo = new ForumStatBo();
		if (opType == 1) {// 增加板块
			dataChanged = boardBo.updateBoard(vo, BoardBo.OPER_OF_INSERT);
		} else if (opType == 2) {// 修改板块
			dataChanged = boardBo.updateBoard(vo, BoardBo.OPER_OF_UPDATE);
		} else if (opType == 3) {
			// 删除板块,将级联删除板块下的所有论坛,主题,回帖
			dataChanged = boardBo.updateBoard(vo, BoardBo.OPER_OF_DELETE);
			//用户主题数积分不会改变
			//网站杂项信息更新
			dataChanged=forumStatBo.reset();
		}

		// 取得所有板块列表
		ArrayList<BoardVo> boardList = boardBo.getAllBoard();
		// 更新板块列表
		context.setAttribute("boardList", boardList);
		ForumBo fo = new ForumBo();
		if (opType == 3) {// 如果是删除板块,将全面更新数据库和内存数据
			// 更新所有论坛列表
			ArrayList<ForumVo> forumList = fo.getAllForum();
			context.setAttribute("forumList", forumList);
			// 更新forumMap
			context.setAttribute("forumMap", fo.getForumMap(forumList));
			//更新网站杂项信息
			ForumStatVo forumInfo = forumStatBo.getForumInfo();
			context.setAttribute("forumInfo", forumInfo);
		}

		if (dataChanged == 1) {
			resp
					.sendRedirect("boardManageQueryPage.jsp?queryPage="
							+ queryPage);
		}
	}

}
